//
//  TopicListController.m
//  BobNews
//
//  Created by lanou3g on 16/5/6.
//  Copyright © 2016年 YJC. All rights reserved.
//

#import "TopicListController.h"
#import "NetWorkRequestManager.h"
#import "TextModelCell.h"
#import "TopicModelCell.h"
#import "TopicModel.h"
#import "TopicFirstModelCell.h"
#import "TopicSecondModelCell.h"
#import "TopicThirdModelCell.h"
#import "TopicFifthModelCell.h"
#import "TopicFourthModelCell.h"
#import "TopicNineModelCell.h"
#import "TopicEightModelCell.h"
#import "TopicSevenModelCell.h"
#import "TopicSixModelCell.h"
#import "LORefresh.h"
#import "UserInfoManager.h"
#import "UMSocial.h"
#import "LoginViewController.h"
#import "CommentViewController.h"
@interface TopicListController ()<UMSocialUIDelegate>
@property (nonatomic,strong) NSMutableArray *topicListArray;
@property (nonatomic,strong) NSString *start;
@property (nonatomic,strong) UIImage *img;
@property (nonatomic,strong) UIImage *img2;
@property (nonatomic,strong) NSString *imgName;
@property (nonatomic,strong) NSString *html;
@end
@implementation TopicListController
- (void)dealloc {
    [self.tableView removeObserver:[self.tableView defaultHeader] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentOffset"];
    [self.tableView removeObserver:[self.tableView defaultFooter] forKeyPath:@"contentSize"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.topicListArray = [NSMutableArray new];

    self.start  = @"10";
    self.title = self.navTitle;
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"TextModelCell" bundle:nil] forCellReuseIdentifier:@"TextModel"];
     [self.tableView registerNib:[UINib nibWithNibName:@"TopicFirstModelCell" bundle:nil] forCellReuseIdentifier:@"TopicFirstModel"];
     [self.tableView registerNib:[UINib nibWithNibName:@"TopicSecondModelCell" bundle:nil] forCellReuseIdentifier:@"TopicSecondModel"];
     [self.tableView registerNib:[UINib nibWithNibName:@"TopicThirdModelCell" bundle:nil] forCellReuseIdentifier:@"TopicThirdModel"];
     [self.tableView registerNib:[UINib nibWithNibName:@"TopicFourthModelCell" bundle:nil] forCellReuseIdentifier:@"TopicFourthModel"];
     [self.tableView registerNib:[UINib nibWithNibName:@"TopicFifthModelCell" bundle:nil] forCellReuseIdentifier:@"TopicFifthModel"];
     [self.tableView registerNib:[UINib nibWithNibName:@"TopicSixModelCell" bundle:nil] forCellReuseIdentifier:@"TopicSixModel"];
     [self.tableView registerNib:[UINib nibWithNibName:@"TopicSevenModelCell" bundle:nil] forCellReuseIdentifier:@"TopicSevenModel"];
     [self.tableView registerNib:[UINib nibWithNibName:@"TopicEightModelCell" bundle:nil] forCellReuseIdentifier:@"TopicEightModel"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TopicNineModelCell" bundle:nil] forCellReuseIdentifier:@"TopicNineModel"];
    
    [self loadDataFromStart:self.start];
    
    
    __weak typeof(self)weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeHeaderDefault refreshingBlock:^{
        [weakSelf.topicListArray removeAllObjects];
        [weakSelf.tableView reloadData];
        [weakSelf loadDataFromStart:weakSelf.start];
    }];
    [self.tableView addRefreshWithRefreshViewType:LORefreshViewTypeFooterDefault refreshingBlock:^{
        [weakSelf loadDataFromStart:weakSelf.start];
    }];
    UIBarButtonItem *commentItem =  [[UIBarButtonItem alloc]initWithTitle:@"评论" style:UIBarButtonItemStylePlain target:self action:@selector(commentItemAction:)];
    
    UIImage *image1 = [UIImage imageNamed:@"分享.png"];
    UIImage *image2 = [image1 imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    UIBarButtonItem *shareBtnItem = [[UIBarButtonItem alloc]initWithImage:image2 style:UIBarButtonItemStylePlain target:self action:@selector(shareBtnAction:)];
    self.navigationItem.rightBarButtonItems =@[shareBtnItem,commentItem];
}
- (void)shareBtnAction:(UIBarButtonItem *)sender {
    if ([UserInfoManager shareManager].uid) {
        [UMSocialSnsService presentSnsIconSheetView:self appKey:@"564913af67e58ed0d7005bb3" shareText:self.html shareImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.model.talkPicture[0]]]] shareToSnsNames:[NSArray arrayWithObjects:UMShareToDouban,UMShareToTencent,UMShareToRenren,UMShareToSina,UMShareToQQ,UMShareToWechatSession, nil] delegate:self];
    }else {
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请先登录" preferredStyle:UIAlertControllerStyleAlert];
        [alertC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self login];
        }]];
        [alertC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        }]];
        [self presentViewController:alertC animated:YES completion:nil];
    }

}

- (void)commentItemAction:(UIBarButtonItem *)sender {
    CommentViewController *commentVC = [[CommentViewController alloc]init];
//    __weak typeof(self)weakSelf = self;
//    commentVC.changeValueBlock = ^(NSString *string)
//    {
//      
//    }
    [self.navigationController pushViewController:commentVC animated:YES];
}
- (void)login {
    LoginViewController *loginVC = [[LoginViewController alloc]init];
    [self.navigationController pushViewController:loginVC animated:YES];
}
- (void)loadDataFromStart:(NSString *)start {
    [NetWorkRequestManager requestUrl:[NSURL URLWithString:[NSString stringWithFormat:@"http://topic.comment.163.com/topic/subject/details/%@.html",self.subjectId]] RequestMethod:GET Params:nil Result:^(NSData *data, NSURLResponse *response, NSError *error) {
        if (data) {
            NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dataDict = jsonDict[@"data"];
            //NSArray *hotList = dataDict[@"hotList"];
            for (NSDictionary *hotListDict in dataDict[@"hotList"]) {
                TopicModel *model = [TopicModel modelWithDictionary:hotListDict];
                [self.topicListArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                [[self.tableView defaultHeader]endRefreshing];
                [[self.tableView defaultFooter]endRefreshing];
            });
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.topicListArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [TopicModelCell cellWithTableView:tableView Model:self.topicListArray[indexPath.row] IndexPath:indexPath];
    // Configure the cell...
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *modelName = NSStringFromClass([self.topicListArray[indexPath.row] class]);
    Class CellClass = NSClassFromString([modelName stringByAppendingString:@"Cell"]);
    return [CellClass height];
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
